package com.ms.oschina.ui.activity;

import java.io.UnsupportedEncodingException;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;

import com.ms.oschina.R;
import com.ms.oschina.api.remote.OkHttpClientManager.OnGetNetResultListener;
import com.ms.oschina.api.remote.OsChinaApi;
import com.ms.oschina.base.BaseActivity;
import com.ms.oschina.bean.Constants;
import com.ms.oschina.bean.HttpResponse;
import com.ms.oschina.bean.LoginUserBean;
import com.ms.oschina.ui.dialog.QuickOptionDialog;
import com.ms.oschina.util.DialogUtils;
import com.ms.oschina.util.LocalBroadcastUtils;
import com.ms.oschina.util.PreferenceUtils;
import com.ms.oschina.util.TDevice;
import com.ms.oschina.util.UiUtils;

public class LoginActivity extends BaseActivity {
	private AutoCompleteTextView tvLoginUsername;
	private ImageView ivClearUsername;
	private EditText tvLoginPassword;
	private ImageView ivClearPassword;

	private void findViews() {
		tvLoginUsername = (AutoCompleteTextView) findViewById(R.id.tv_login_username);
		ivClearUsername = (ImageView) findViewById(R.id.iv_clear_username);
		tvLoginPassword = (EditText) findViewById(R.id.tv_login_password);
		ivClearPassword = (ImageView) findViewById(R.id.iv_clear_password);
	}

	@Override
	protected int getLayoutId() {
		return R.layout.activity_login;
	}

	@Override
	protected void initView() {
		findViews();
	}

	@Override
	protected void initData() {
		ivClearUsername.setOnClickListener(this);
		ivClearPassword.setOnClickListener(this);
	}

	@Override
	protected void initEvent() {
		TextWatcher listener = new ClearTextTextWatcher();
		// 设置点击事件
		tvLoginUsername.addTextChangedListener(listener);

		tvLoginPassword.addTextChangedListener(listener);
	}

	public void login(View view) {
		if (checkLogin()) {
			// 登录
			UiUtils.showToast("登录");
			// 显示对话框
			final QuickOptionDialog dialog = DialogUtils.showLoginDialog(this);
			// 登录
			try {
				OsChinaApi.login(tvLoginUsername.getText().toString(),
						tvLoginPassword.getText().toString(),
						new OnGetNetResultListener<LoginUserBean>() {
							@Override
							public void onGetNetResult(int requestCode,
									HttpResponse<LoginUserBean> result) {
								dialog.dismiss();
								if (result.e != null || result.errorCode == 0) {// 未登陆成功
									String errorMessage = (String) result.obj;
									if (!TextUtils.isEmpty(errorMessage)) {
										UiUtils.showToast(errorMessage);
									}
									return;
								}

								saveUserInfo(result);
								sendBroad();
								finish();
							}
						});
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
	}

	protected void saveUserInfo(HttpResponse<LoginUserBean> result) {
		// 标记以登录
		PreferenceUtils.setPrefBoolean(UiUtils.getContext(),
				Constants.IS_LOGIN, true);

		int id = result.response.getUser().getId();
		PreferenceUtils.setPrefInt(UiUtils.getContext(), Constants.UID, id);
		PreferenceUtils.setPrefString(UiUtils.getContext(), Constants.USERNAME,
				result.response.getUser().getName());
	}

	private void sendBroad() {
		Intent intent = new Intent(Constants.ACTION_EXTERNAL_USERCHANGE);
		LocalBroadcastUtils.sendBroad(intent);
	}

	/**
	 * 检测登录是否合法
	 * 
	 * @return
	 */
	private boolean checkLogin() {
		if (!TDevice.hasInternet()) {
			UiUtils.showToast(UiUtils.getString(R.string.tip_no_internet));
			return false;
		}
		String uName = tvLoginUsername.getText().toString();

		if (TextUtils.isEmpty(uName)) {
			UiUtils.showToast(UiUtils
					.getString(R.string.tip_please_input_username));
			tvLoginUsername.requestFocus();
			return false;
		}

		// 不检测邮箱

		String pwd = tvLoginPassword.getText().toString();
		if (TextUtils.isEmpty(pwd)) {
			UiUtils.showToast(UiUtils
					.getString(R.string.tip_please_input_password));
			tvLoginPassword.requestFocus();
			return false;
		}

		return true;
	}

	@Override
	protected void processClick(View v) {
		int id = v.getId();
		if (id == R.id.iv_clear_username) {
			tvLoginUsername.setText("");
		} else if (id == R.id.iv_clear_password) {
			tvLoginPassword.setText("");
		}
	}

	@Override
	protected CharSequence getBackActionBarTitle() {
		return UiUtils.getString(R.string.login);
	}

	class ClearTextTextWatcher implements TextWatcher {

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			String userName = tvLoginUsername.getText().toString();

			if (userName.length() > 0) {
				ivClearUsername.setVisibility(0);
			} else {
				ivClearUsername.setVisibility(8);
			}

			String password = tvLoginPassword.getText().toString();

			if (password.length() > 0) {
				ivClearPassword.setVisibility(0);
			} else {
				ivClearPassword.setVisibility(8);
			}
		}

		@Override
		public void afterTextChanged(Editable s) {

		}

	}

}
